import fitz
import logging
from PyPDF2 import PdfReader, PdfWriter

class PDFHandler:
    def __init__(self):
        self.current_pdf = None
        self.file_path = None
        self.modifications = {}  # 存储修改信息

    def open_pdf(self, file_path):
        try:
            self.file_path = file_path
            self.current_pdf = fitz.open(file_path)
            self.modifications = {}
            return True
        except Exception as e:
            logging.error(f"PDF打开错误: {str(e)}")
            return False

    def save_pdf(self, save_path):
        try:
            if not self.current_pdf:
                return False
                
            # 应用修改并保存
            self.current_pdf.save(save_path)
            return True
        except Exception as e:
            logging.error(f"PDF保存错误: {str(e)}")
            return False

    def get_page_count(self):
        return len(self.current_pdf) if self.current_pdf else 0

    def rotate_page(self, page_num, angle):
        try:
            page = self.current_pdf[page_num]
            page.set_rotation(angle)
            return True
        except Exception as e:
            logging.error(f"页面旋转错误: {str(e)}")
            return False

    def delete_page(self, page_num):
        try:
            self.current_pdf.delete_page(page_num)
            return True
        except Exception as e:
            logging.error(f"页面删除错误: {str(e)}")
            return False
